Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [1]:
# Load pickled data
import pickle

training_file = "traffic-signs-data/train.p"
validation_file = "traffic-signs-data/valid.p"
testing_file = "traffic-signs-data/test.p"
sign_names_file = 'signnames.csv'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
with open(sign_names_file) as f:
    class_names = list(map(lambda x: x.strip().split(',')[1], f.readlines()))[1:]
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

In [2]:
import numpy as np

n_train = len(X_train)
n_valid = len(X_valid)
n_test = len(X_test)

image_shape = X_train[0].shape
n_classes = len(np.unique(y_train))

print("Number of training examples =", n_train)
print("Number of validation examples =", n_valid)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of validation examples = 4410
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?


Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

In [3]:
import matplotlib.pyplot as plt
%matplotlib inline

indexes = np.argwhere(y_train == 0)
plt.figure(figsize=(10, 30))
plt.imshow(np.hstack(X_train[indexes[0:15, 0]]))
plt.axis('off')
plt.show()
In [4]:
from sklearn.utils import shuffle

# the sample image from each class
fig, ax = plt.subplots(figsize=(15, 30))
examples = []
for cls in range(n_classes):
    indexes = np.argwhere(y_train == cls)
    np.random.shuffle(indexes)
    examples.append(np.hstack(X_train[indexes[0:15, 0]]))
ax.imshow(np.vstack(examples))
ax.set_yticks(np.arange(n_classes) * image_shape[0] + image_shape[0] / 2)
ax.set_yticklabels(class_names)
ax.set_xticks([])
plt.show()
In [5]:
# histogram
plt.hist(y_train, bins=n_classes, rwidth=0.8)
plt.show()
print("min train size is {}.".format(np.min([np.sum(y_train == i) for i in range(n_classes)])))
min train size is 180.
In [6]:
plt.hist(y_valid, bins=n_classes, rwidth=0.8)
plt.show()

Pre-process the Data Set (normalization, grayscale, etc.)

Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.

Other pre-processing steps are optional. You can try different techniques to see if it improves performance.

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [7]:
print('# Original data')
print('Shape:', X_train.shape)
print('Average:', np.mean(X_train))
# Original data
Shape: (34799, 32, 32, 3)
Average: 82.6775890369964
In [8]:
import cv2

def grayscale(img):
    return cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

def equalize_hist(img):
    return cv2.equalizeHist(img)

def normalize(img):
    min_, max_ = np.min(img), np.max(img)
    return (img - min_) / (max_ - min_) * 2 - 1

def preprocess_each(img):
    return np.expand_dims(normalize(equalize_hist(grayscale(img))), axis=2)

def preprocess(dataset):
    return np.array([preprocess_each(img) for img in dataset])

def one_hot_encoder(y):
    one_hot_y = np.zeros((len(y), n_classes))
    one_hot_y[range(len(y)), y] = 1 
    return one_hot_y
In [9]:
X_train = preprocess(X_train)
X_valid = preprocess(X_valid)
X_test  = preprocess(X_test)

print('# Preprocessed data')
print('Shape:', X_train.shape)
print('Average:', np.mean(X_train))

y_one_hot_train = one_hot_encoder(y_train)
y_one_hot_valid = one_hot_encoder(y_valid)
y_one_hot_test  = one_hot_encoder(y_test)
# Preprocessed data
Shape: (34799, 32, 32, 1)
Average: 0.03010814641077417
In [10]:
fig, ax = plt.subplots(figsize=(10, 30))
examples = []
for cls in range(n_classes):
    indexes = np.argwhere(y_train == cls)
    np.random.shuffle(indexes)
    examples.append(np.hstack(X_train[indexes[0:15, 0]][:, :, :, 0]))
ax.imshow(np.vstack(examples), cmap='gray')
ax.set_yticks(np.arange(n_classes) * image_shape[0] + image_shape[0] / 2)
ax.set_yticklabels(class_names)
ax.set_xticks([])
plt.show()

Data Augumentation

In [15]:
from tqdm import tqdm

alpha = 1.
augmented_X = []
augmented_y = []

for _ in tqdm(range(5000)):
    indexes = np.arange(n_train)
    np.random.shuffle(indexes)
    i, j = indexes[:2]
    lambda_ = np.random.beta(alpha, alpha)
    augmented_X.append(normalize(X_train[i] * lambda_ + X_train[j] * (1 - lambda_)))
    augmented_y.append(y_one_hot_train[i] * lambda_ + y_one_hot_train[j] * (1 - lambda_))
100%|████████████████████████████████████████████████████████████████████████████| 5000/5000 [00:03<00:00, 1652.97it/s]
In [32]:
plt.imshow(augmented_X[200][:,:,0], cmap='gray')
print("Mixing [{}] and [{}]".format(class_names[1], class_names[28]))
Mixing [Speed limit (30km/h)] and [Children crossing]
In [33]:
X_train = np.concatenate([X_train, np.array(augmented_X)])
y_one_hot_train = np.concatenate([y_one_hot_train, np.array(augmented_y)])

Model Architecture

In [34]:
import tensorflow as tf
from tensorflow.contrib.layers import flatten

def batch_normalization(inputs, is_training=None, decay=0.99):
    epsilon = 1e-5
    out_dim = inputs.get_shape()[-1]
    scale = tf.Variable(tf.ones([out_dim]))
    beta = tf.Variable(tf.zeros([out_dim]))
    pop_mean = tf.Variable(tf.zeros([out_dim]), trainable=False)
    pop_var = tf.Variable(tf.ones([out_dim]), trainable=False)

    if is_training == None:
        return tf.nn.batch_normalization(inputs, pop_mean, pop_var, beta, scale, epsilon)

    axes = list(range(len(inputs.get_shape()) - 1))
    batch_mean, batch_var = tf.nn.moments(inputs, axes)

    ema = tf.train.ExponentialMovingAverage(decay=decay)

    def update():
        ema_apply_op = ema.apply([batch_mean, batch_var])
        with tf.control_dependencies([ema_apply_op]):
            return tf.nn.batch_normalization(inputs, tf.identity(batch_mean), tf.identity(batch_var), beta, scale, epsilon)
    
    def average():
        train_mean = pop_mean.assign(ema.average(batch_mean))
        train_var = pop_var.assign(ema.average(batch_var))
        with tf.control_dependencies([train_mean, train_var]):
            return tf.nn.batch_normalization(inputs, train_mean, train_var, beta, scale, epsilon)

    return tf.cond(is_training, update, average)
        
def weight_variable(shape):
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    return tf.Variable(tf.truncated_normal(shape=shape, mean = 0, stddev = 0.1))

def conv2d(x, W, k):
    return tf.nn.conv2d(x, W, strides=[1, k, k, 1], padding='VALID')

def max_pool(x, k):
    return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='VALID')

def LeNet(x):
    # SOLUTION: Layer 1: Convolutional. Input = 32x32x1. Output = 28x28x6.
    conv1_W = weight_variable(shape=(5, 5, 1, 6))
    conv1   = conv2d(x, conv1_W, k=1)
    conv1   = batch_normalization(conv1, is_training)

    # SOLUTION: Activation.
    conv1 = tf.nn.relu(conv1)

    # SOLUTION: Pooling. Input = 28x28x6. Output = 14x14x6.
    conv1 = max_pool(conv1, k=2)

    # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
    conv2_W = weight_variable(shape=(5, 5, 6, 16))
    conv2   = conv2d(conv1, conv2_W, k=1)
    conv2   = batch_normalization(conv2, is_training)
    
    # SOLUTION: Activation.
    conv2 = tf.nn.relu(conv2)

    # SOLUTION: Pooling. Input = 10x10x16. Output = 5x5x16.
    conv2 = max_pool(conv2, k=2)

    # SOLUTION: Flatten. Input = 5x5x16. Output = 400.
    fc0   = flatten(conv2)
    
    # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
    fc1_W = weight_variable(shape=(400, 120))
    fc1   = tf.matmul(fc0, fc1_W)
    fc1   = batch_normalization(fc1, is_training)
    
    # SOLUTION: Activation.
    fc1    = tf.nn.relu(fc1)

    # SOLUTION: Dropout.
    fc1    = tf.nn.dropout(fc1, keep_prob)

    # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
    fc2_W  = weight_variable(shape=(120, 84))
    fc2    = tf.matmul(fc1, fc2_W)
    fc2    = batch_normalization(fc2, is_training)
    
    # SOLUTION: Activation.
    fc2    = tf.nn.relu(fc2)
    
    # SOLUTION: Dropout.
    fc2    = tf.nn.dropout(fc2, keep_prob)

    # SOLUTION: Layer 5: Fully Connected. Input = 84. Output = 43.
    fc3_W  = weight_variable(shape=(84, 43))
    fc3_b  = tf.Variable(tf.zeros(43))
    logits = tf.matmul(fc2, fc3_W) + fc3_b
    
    return logits
C:\Users\Yuma\Anaconda3\lib\site-packages\h5py\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [35]:
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.float32, (None, n_classes))
is_training = tf.placeholder(tf.bool)
keep_prob = tf.placeholder(tf.float32) 

rate = 0.03
EPOCHS = 50
BATCH_SIZE = 128

logits = LeNet(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)

correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()

def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation,
                            feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0, is_training: False})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples

history_train = []
history_valid = []
history_test = []

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train)
    
    print("Training...")
    print()
    for i in range(EPOCHS):
        X_train, y_one_hot_train = shuffle(X_train, y_one_hot_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train[offset:end], y_one_hot_train[offset:end]
            sess.run(training_operation,
                     feed_dict={x: batch_x, y: batch_y, keep_prob: 0.5, is_training: True})
        
        training_accuracy = evaluate(X_train, y_one_hot_train)
        validation_accuracy = evaluate(X_valid, y_one_hot_valid)
        test_accuracy = evaluate(X_test, y_one_hot_test)
        
        history_train.append(training_accuracy)
        history_valid.append(validation_accuracy)
        history_test.append(test_accuracy)

        if (i+1) % 5 == 0:
            print("EPOCH {} ...".format(i+1))
            print("Training Accuracy = {:.3f}".format(training_accuracy))
            print("Validation Accuracy = {:.3f}".format(validation_accuracy))
            print("Test Accuracy = {:.3f}".format(test_accuracy))
            print()
        
    saver.save(sess, './lenet')
    print("Model saved")
Training...

EPOCH 5 ...
Training Accuracy = 0.949
Validation Accuracy = 0.956
Test Accuracy = 0.928

EPOCH 10 ...
Training Accuracy = 0.962
Validation Accuracy = 0.962
Test Accuracy = 0.946

EPOCH 15 ...
Training Accuracy = 0.956
Validation Accuracy = 0.955
Test Accuracy = 0.942

EPOCH 20 ...
Training Accuracy = 0.965
Validation Accuracy = 0.972
Test Accuracy = 0.948

EPOCH 25 ...
Training Accuracy = 0.968
Validation Accuracy = 0.968
Test Accuracy = 0.949

EPOCH 30 ...
Training Accuracy = 0.968
Validation Accuracy = 0.968
Test Accuracy = 0.952

EPOCH 35 ...
Training Accuracy = 0.966
Validation Accuracy = 0.971
Test Accuracy = 0.949

EPOCH 40 ...
Training Accuracy = 0.969
Validation Accuracy = 0.967
Test Accuracy = 0.946

EPOCH 45 ...
Training Accuracy = 0.969
Validation Accuracy = 0.974
Test Accuracy = 0.947

EPOCH 50 ...
Training Accuracy = 0.971
Validation Accuracy = 0.975
Test Accuracy = 0.952

Model saved
In [43]:
plt.figure(figsize=(10,6))
plt.plot(range(1, EPOCHS+1), history_train)
plt.plot(range(1, EPOCHS+1), history_valid)
plt.plot(range(1, EPOCHS+1), history_test)
plt.legend(['training', 'validation', 'test'], loc='lower right')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.xlim([1, EPOCHS])
plt.show()

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [44]:
from pathlib import Path

test_images = []
test_labels = np.array([23, 12, 3, 35, 25])

files = sorted(Path('test_images/').glob('*'))
fig, ax = plt.subplots(1, 5, figsize=(15, 8))
ax = ax.ravel()

for i, file in enumerate(files):
    img = cv2.cvtColor(cv2.imread(file.as_posix()), cv2.COLOR_BGR2RGB)
    ax[i].imshow(img)
    ax[i].set_title(class_names[test_labels[i]])
    ax[i].axis('off')
    test_images.append(img)
    
test_images = preprocess(test_images)

Predict the Sign Type for Each Image

In [45]:
with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))
    predictions = sess.run(tf.argmax(logits, 1),
                           feed_dict={x: test_images, keep_prob: 1.0, is_training: False})
print("")

for (test_label, prediction) in zip(test_labels, predictions):
    if test_label == prediction:
        print("[PASS]")
    else:
        print("[FAIL] test_label: {} ({}), prediction: {} ({})".format(test_label, 
                                                                       class_names[test_label],
                                                                       prediction,
                                                                       class_names[prediction]))
INFO:tensorflow:Restoring parameters from .\lenet

[FAIL] test_label: 23 (Slippery road), prediction: 31 (Wild animals crossing)
[PASS]
[PASS]
[PASS]
[PASS]

Analyze Performance

Test Accuracy (new images) = 0.800

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [48]:
with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))
    top_k_outputs = sess.run(tf.nn.top_k(tf.nn.softmax(logits), k=5),
                             feed_dict={x: test_images, keep_prob: 1.0, is_training: False})

print(top_k_outputs.values)
print()
print(top_k_outputs.indices)
INFO:tensorflow:Restoring parameters from .\lenet
[[2.3995972e-01 2.2077125e-01 7.2365433e-02 6.1163075e-02 5.4212496e-02]
 [9.9867070e-01 3.7242667e-04 2.8465598e-04 1.9926122e-04 1.6272382e-04]
 [9.9690211e-01 2.9591322e-03 4.4942466e-05 2.1605601e-05 1.5273166e-05]
 [9.7529638e-01 9.6605644e-03 4.0548309e-03 2.4080700e-03 1.8264671e-03]
 [9.9588275e-01 1.0834950e-03 7.2833861e-04 6.6530926e-04 4.7763699e-04]]

[[31 18  5 11 10]
 [12 14  5 13  8]
 [ 3  5  2  7 12]
 [35  3 12 33 13]
 [25 10  5 18 12]]

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In [ ]: